<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\shop_admin\service;

use app\shop_admin\model\Area;
use app\shop_admin\model\Distribution;
use app\shop_admin\model\Order;
use app\shop_admin\model\Transport;
use app\utils\Dada;
use app\utils\Meituan;
use think\Exception;

class DistributionService
{
    private $user;

    public function __construct()
    {
        global $user;
        $this->user = $user;
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(string $data)
    {
        $res = Distribution::where('mall_id', $this->user->mall_id)
            ->where('merchant_id', $this->user->merchant_id)
            ->where('store_id', $data)
            ->find();
        return [HTTP_SUCCESS, $res];
    }

    /**
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(array $data)
    {
        try {
            $find = Distribution::where(["mall_id" => $this->user->mall_id, "merchant_id" => $this->user->merchant_id,"store_id" => $data['store_id']])->find();
            $data = [
                "store_id" => $data['store_id'] ?? null,
                "mall_id" => $this->user->mall_id,
                "merchant_id" => $this->user->merchant_id,
                "type" => $data['type'],
                "third_party" => $data['third_party'],
                "config" => $data['config'],//config 第三方配置信息有多个配置数组
                "shop_address" => $data['shop_address'] ?? null,
                "area" => $data['area'] ?? null,
                "area_data" => $data['area_data'] ?? null,
                "area_config" => $data['area_config'] ?? null,
                "divide_config" => $data["divide_config"] ?? null,//最多10组
                "divide_type" => $data['divide_type'] ?? null,
                "renewal_charge" => $data['renewal_charge'] ?? null,
                "billing_method" => $data['billing_method'] ?? null,//计费方式
                "gaude_key" => $data['gaude_key'] ?? null
            ];
            if ($find)
                Distribution::where(["mall_id" => $this->user->mall_id, "merchant_id" => $this->user->merchant_id, "store_id" => $data['store_id']])
                    ->update($data, ["type", "third_party", "config", "shop_address", "area", "divide_config", "divide_type", "renewal_charge", "billing_method", "gaude_key"]);
            else
                Distribution::create($data);
        } catch (Exception $exception) {
            return [HTTP_INVALID, $exception->getMessage()];
        }
        return [HTTP_SUCCESS, "成功"];
    }

    /**
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getJurisdiction(array $data)
    {
       
        $address = explode(',', $data['address']);
        $result[] = $address[1] == "市辖区" ? ['name', '=', $address[0]] : ['name', '=', $address[1]];
        $area = Area::where($result)->find();
        $list = [];
        if ($address[1] == "市辖区") {
            $parent = Area::where('parent_code', $area['area_code'])->where('name', $address[1])->find();
            $list[] = ['parent_code', '=', $parent['area_code']];
        } else {
            $list[] = ['parent_code', '=', $area['area_code']];
        }
        
        $res = Area::where($list)->field('name,area_code')
            ->select();
        return [HTTP_SUCCESS, $res];
    }

    /**获取联系我们
     *
     */
    public function getMyContact()
    {
        $res = Distribution::where(['mall_id' => $this->user->mall_id, 'merchant_id' => $this->user->merchant_id])
            ->field('shop_address,shop_region,contacts,contact_phone_one,contact_phone_two,coordinate')
            ->find();
        return [HTTP_SUCCESS, $res];
    }

    /**更新我的联系人
     * @param $data
     * @return array
     */
    public function saveMyContact($data)
    {
        $up = Distribution::where(['mall_id' => $this->user->mall_id, 'merchant_id' => $this->user->merchant_id])
            ->update($data);
        return [HTTP_SUCCESS, $up];
    }

    public function transport()
    {
        $res = [];
        $distr = Distribution::where(['mall_id' => $this->user->mall_id, 'merchant_id' => $this->user->merchant_id])->find();
        $ids = explode(',', $distr['type']);
        if (in_array(2, $ids))
            $res = Transport::where('id', 'IN', explode(',', $distr['third_party']))->select();
        if (in_array(1, $ids)) $res[] = ['id' => 1, 'name' => '商家配送'];
        return [HTTP_SUCCESS, $res];
    }

    /**后端选择配送
     * @param array $data
     * @return array
     */
    public function upDistributionType(array $data)
    {
        $up = Order::where('id', $data['order_id'])->update(['distribution_id' => $data['distribution_id']]);
        return [HTTP_SUCCESS, $up];
    }

    /**美团预发单
     * @param array $data
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function advanceOrder(array $data, array $find)
    {
        $config = Distribution::where('mall_id', $this->user->mall_id)->where('merchant_id', $this->user->merchant_id)->find();
        $shop = json_decode($config['config'], true);
        $meituan = (new Meituan());
        $flag = $meituan->shop(['shop_id' => $shop['app_store_number']]);
        $arr = $find->toArray();
        $total = array_sum(array_column($arr['orderCommodity'], 'weight'));
        $res = $this->coordinate($find['address'], $config);
        $data = [
            'delivery_id' => uniqid(),
            'order_id' => $find['id'],
            'outer_order_source_desc' => "微信公众号",
            'shop_id' => $shop['app_store_number'],
            'delivery_service_code' => 4031,
            'receiver_name' => $find['userAddress']['consignee'],
            'receiver_address' => $find['address'],
            'receiver_phone' => $find['iphone'],
            'receiver_lng' => $res['location']['longitude'],
            'receiver_lat' => $res['location']['latitude'],
            'pay_type_code' => $flag['pay_type_codes'],
            'goods_weight' => $total,
        ];
        return $meituan->advanceOrder($data);
    }

    private function coordinate(string $address, array $config)
    {
        $url = "https://restapi.amap.com/v3/geocode/geo?key=" . $config['gaude_key'] . "&address=" . $address . "&output=JSON";
        return curl_get($url);
    }

    /**达达配送
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function dadaAdvanceOrder(array $data, array $find)
    {
        $config = Distribution::where(['mall_id' => $this->user->mall_id, 'merchant_id' => $this->user->merchant_id])->find();
        $order = Order::with(['orderCommodity' => function ($query) {
            $query->alias('y')
                ->join('commodity c', 'y.commodity_id=c.id', 'LEFT')
                ->field('y.*,c.weight');
        }, 'userAddress'])
            ->find($data['order_id'])
            ->toArray();
        $total = array_sum(array_column($order['orderCommodity'], 'weight'));
        $res = [
            "shop_no" => $config['app_store_number'],
            'origin_id' => $data['order_id'],
            'city_code' => '',
            'cargo_price' => $order['money'],
            'is_prepay' => 0,
            'receiver_name' => $order['userAddress']['consignee'],
            'receiver_address' => $order['userAddress']['address'],
            'callback' => '',
            'cargo_weight' => $total
        ];
        return (new Dada())->deliverFee($res);
    }

    /**
     * array $data
     */
    public function placeOrder(array $data)
    {
        $find = Order::with(['orderCommodity' => function ($query) {
            $query->alias('y')
                ->join('commodity c', 'y.commodity_id=c.id', 'LEFT')
                ->field('y.*,c.weight');
        }, 'userAddress'])
            ->find($data['order_id']);

        if ($find['distribution_id'] == 2)
            $res = $this->advanceOrder($data, $find);
        elseif ($find['distribution_id'] == 3)
            $res = $this->dadaAdvanceOrder($data, $find);

        if (empty($res['code'])) {

        }


    }


}